import json
import re
import time
from DrissionPage import ChromiumPage
from DrissionPage._functions.keys import Keys
import os
import shutil
from util.logger import get_looger

logger = get_looger("京东.log", __file__)


def clean_filename(filename):
    """清理文件名中的非法字符"""
    return re.sub(r'[<>:"/\\|?*]', '', filename)


logger.info("爬虫启动......")

try:
    root = 'static/京东/'
    if os.path.exists(root):
        shutil.rmtree(root)
    os.makedirs(root)

    # path = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
    # ChromiumOptions().set_browser_path(path).save()

    dp = ChromiumPage()
    dp.get('https://www.jd.com')
    dp.ele('css:#key').input('键盘')
    dp.ele('css:#key').input(Keys.ENTER)
    time.sleep(2)
    dp.scroll.to_bottom()
    time.sleep(2)
    lis = dp.eles('css:._card_8v3rv_40')
    # print(lis)
    # items = {}
    for li in lis:
        title = li.ele('css:._info_8v3rv_44 span').text
        price = li.ele('css:._container_uqsva_2 span').text
        buys = li.ele('css:._goods_volume_container_1xkku_1 span').text
        belongs = li.ele('css:._shopFloor_d19t5_1 span').text

        # 清理文件名
        clean_title = clean_filename(title)
        if not clean_title:  # 如果清理后为空，使用默认名称
            clean_title = "未知产品"

        # 使用清理后的文件名
        with open(f"{root}{clean_title}.txt", "w", encoding="utf-8") as f:
            f.write(f"标题：{title}\n")
            f.write(f"价格：{price}\n")
            f.write(f"销量：{buys}\n")
            f.write(f"所属：{belongs}\n")

        logger.info(f"已保存: {clean_title}.txt")

except Exception as e:
    logger.error(e)